<template>
  <div class="min-h-screen bg-base-100">
    <div class="blog-container">
      <div class="flex items-center justify-between mb-6">
        <h1 class="text-3xl font-bold">标签管理</h1>
        
        <button @click="openNewTagModal = true" class="btn btn-primary gap-2">
          <icon-plus class="w-5 h-5" />
          新建标签
        </button>
      </div>
      
      <div class="card bg-base-100 shadow-xl border border-base-200 mb-8">
        <div class="card-body">
          <!-- 标签搜索 -->
          <div class="relative mb-6">
            <icon-search class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input 
              v-model="searchQuery" 
              type="text" 
              placeholder="搜索标签..." 
              class="input input-bordered w-full pl-10" />
          </div>
          
          <!-- 标签列表 -->
          <div v-if="filteredTags.length > 0" class="overflow-x-auto">
            <table class="table w-full">
              <thead>
                <tr>
                  <th>标签名</th>
                  <th>Slug</th>
                  <th>文章数</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="tag in filteredTags" :key="tag.id" class="hover">
                  <td>
                    <div class="flex items-center space-x-3">
                      <div class="badge badge-lg">{{ tag.name }}</div>
                    </div>
                  </td>
                  <td>{{ tag.slug }}</td>
                  <td>{{ getPostCountByTag(tag.id) }}</td>
                  <td>
                    <div class="flex items-center space-x-2">
                      <button @click="editTag(tag)" class="btn btn-sm btn-ghost">
                        <icon-edit class="w-4 h-4" />
                      </button>
                      <button @click="confirmDeleteTag(tag)" class="btn btn-sm btn-ghost text-error">
                        <icon-trash class="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 无标签提示 -->
          <div v-else class="text-center py-12">
            <icon-tag-off class="w-16 h-16 mx-auto text-base-300" />
            <p class="mt-4 text-lg">暂无标签</p>
            <p v-if="searchQuery" class="mt-2 text-base-content/70">
              尝试使用其他搜索词
            </p>
            <button 
              v-if="searchQuery" 
              @click="searchQuery = ''" 
              class="btn btn-outline btn-sm mt-4">
              清除搜索
            </button>
          </div>
        </div>
      </div>
      
      <!-- 标签使用分析 -->
      <div class="card bg-base-100 shadow-xl border border-base-200">
        <div class="card-body">
          <h2 class="card-title mb-6">标签使用分析</h2>
          
          <div v-if="sortedTagsWithCount.length > 0" class="space-y-6">
            <!-- 标签统计图表 -->
            <div class="h-64 bg-base-200 rounded-lg flex items-end justify-around p-4">
              <div 
                v-for="tag in sortedTagsWithCount.slice(0, 10)" 
                :key="tag.id" 
                class="flex flex-col items-center">
                <div 
                  class="bg-primary w-16" 
                  :style="{ height: `${(tag.count / mostUsedTagCount) * 180}px` }"></div>
                <div class="mt-2 text-xs text-center w-20 overflow-hidden text-ellipsis">
                  {{ tag.name }}
                </div>
              </div>
              <div v-if="sortedTagsWithCount.length > 10" class="flex flex-col items-center">
                <div 
                  class="bg-base-300 w-16" 
                  :style="{ height: `${(otherTagsCount / mostUsedTagCount) * 180}px` }"></div>
                <div class="mt-2 text-xs text-center w-20 overflow-hidden text-ellipsis">
                  其他标签
                </div>
              </div>
            </div>
            
            <!-- 常用标签 -->
            <div>
              <h3 class="font-bold mb-4">常用标签</h3>
              <div class="flex flex-wrap gap-2">
                <div 
                  v-for="tag in sortedTagsWithCount.slice(0, 8)" 
                  :key="tag.id" 
                  class="badge badge-lg badge-primary">
                  {{ tag.name }} ({{ tag.count }})
                </div>
              </div>
            </div>
            
            <!-- 未使用标签 -->
            <div v-if="unusedTags.length > 0">
              <h3 class="font-bold mb-4">未使用标签</h3>
              <div class="flex flex-wrap gap-2">
                <div 
                  v-for="tag in unusedTags" 
                  :key="tag.id" 
                  class="badge badge-lg badge-outline">
                  {{ tag.name }}
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="text-center py-12">
            <icon-bar-chart-2 class="w-16 h-16 mx-auto text-base-300" />
            <p class="mt-4">暂无标签使用数据</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新建标签模态框 -->
    <dialog :class="{ 'modal-open': openNewTagModal }" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">{{ editingTag ? '编辑标签' : '新建标签' }}</h3>
        
        <div class="form-control mb-4">
          <label class="label">
            <span class="label-text">标签名称</span>
          </label>
          <input 
            v-model="newTagName" 
            type="text" 
            placeholder="输入标签名称" 
            class="input input-bordered w-full" />
        </div>
        
        <div class="form-control mb-6">
          <label class="label">
            <span class="label-text">标签别名 (Slug)</span>
          </label>
          <input 
            v-model="newTagSlug" 
            type="text" 
            placeholder="输入标签别名，用于URL" 
            class="input input-bordered w-full" />
          <label class="label">
            <span class="label-text-alt">如果留空，将自动根据标签名生成</span>
          </label>
        </div>
        
        <div class="modal-action">
          <button @click="cancelTagEdit" class="btn">取消</button>
          <button @click="saveTag" class="btn btn-primary" :disabled="!newTagName.trim()">
            {{ editingTag ? '保存' : '创建' }}
          </button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button @click="cancelTagEdit">关闭</button>
      </form>
    </dialog>
    
    <!-- 删除确认模态框 -->
    <dialog :class="{ 'modal-open': openDeleteConfirm }" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg mb-4">确认删除</h3>
        <p class="py-4">
          确定要删除标签 <span class="font-bold">{{ tagToDelete?.name }}</span> 吗？
        </p>
        <p v-if="getPostCountByTag(tagToDelete?.id || '') > 0" class="text-warning">
          <icon-alert-triangle class="w-4 h-4 inline-block mr-1" />
          有 {{ getPostCountByTag(tagToDelete?.id || '') }} 篇文章使用了此标签，删除后这些文章将不再关联此标签。
        </p>
        <div class="modal-action">
          <button @click="openDeleteConfirm = false" class="btn">取消</button>
          <button @click="deleteTag" class="btn btn-error">确认删除</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button @click="openDeleteConfirm = false">关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useBlogStore } from '@/stores/blogStore';
import type { Tag } from '@/types';

const blogStore = useBlogStore();

// 搜索
const searchQuery = ref('');

// 标签操作
const openNewTagModal = ref(false);
const openDeleteConfirm = ref(false);
const newTagName = ref('');
const newTagSlug = ref('');
const editingTag = ref<Tag | null>(null);
const tagToDelete = ref<Tag | null>(null);

// 获取所有标签
const allTags = computed(() => blogStore.tags);

// 过滤标签
const filteredTags = computed(() => {
  if (!searchQuery.value) return allTags.value;
  
  const query = searchQuery.value.toLowerCase();
  return allTags.value.filter(
    tag => tag.name.toLowerCase().includes(query) || tag.slug.toLowerCase().includes(query)
  );
});

// 获取标签关联的文章数量
const getPostCountByTag = (tagId: string) => {
  return blogStore.getAllPosts.filter(post => post.tags.includes(tagId)).length;
};

// 带有使用计数的标签
const tagsWithCount = computed(() => {
  return allTags.value.map(tag => ({
    ...tag,
    count: getPostCountByTag(tag.id),
  }));
});

// 按使用数量排序的标签
const sortedTagsWithCount = computed(() => {
  return [...tagsWithCount.value].sort((a, b) => b.count - a.count);
});

// 获取使用最多的标签计数（用于图表）
const mostUsedTagCount = computed(() => {
  if (sortedTagsWithCount.value.length === 0) return 0;
  return sortedTagsWithCount.value[0].count;
});

// 其他标签的总使用次数（图表中超出显示范围的）
const otherTagsCount = computed(() => {
  if (sortedTagsWithCount.value.length <= 10) return 0;
  return sortedTagsWithCount.value.slice(10).reduce((sum, tag) => sum + tag.count, 0);
});

// 未使用的标签
const unusedTags = computed(() => {
  return tagsWithCount.value.filter(tag => tag.count === 0);
});

// 编辑标签
const editTag = (tag: Tag) => {
  editingTag.value = tag;
  newTagName.value = tag.name;
  newTagSlug.value = tag.slug;
  openNewTagModal.value = true;
};

// 准备删除标签
const confirmDeleteTag = (tag: Tag) => {
  tagToDelete.value = tag;
  openDeleteConfirm.value = true;
};

// 执行删除标签
const deleteTag = () => {
  if (tagToDelete.value) {
    blogStore.deleteTag(tagToDelete.value.id);
    openDeleteConfirm.value = false;
    tagToDelete.value = null;
  }
};

// 取消标签编辑
const cancelTagEdit = () => {
  openNewTagModal.value = false;
  editingTag.value = null;
  newTagName.value = '';
  newTagSlug.value = '';
};

// 保存标签
const saveTag = () => {
  if (!newTagName.value.trim()) return;
  
  // 如果没有提供slug，根据名称生成
  const slug = newTagSlug.value.trim() || newTagName.value.trim().toLowerCase().replace(/\s+/g, '-');
  
  if (editingTag.value) {
    // 更新标签
    blogStore.updateTag(editingTag.value.id, {
      name: newTagName.value.trim(),
      slug,
    });
  } else {
    // 创建新标签
    blogStore.addTag({
      name: newTagName.value.trim(),
      slug,
    });
  }
  
  // 清空并关闭模态框
  cancelTagEdit();
};
</script> 